const {pageBase, listBase, getBase, saveBase, delBase} = require("../service/base.service");
const Dictionary = require("../model/dictionary.model");
const {pgParam} = require("../tool/toolPage");
const {whereBase, whereNoNull} = require("../tool/tool");
const {Op} = require("sequelize");
const {resSuccess, resBool, throwError} = require("../tool/toolBase");
const {errDoMsg} = require("../constant/comConstant");

const loopDic = (pobj, allDic) => {
    if (pobj) {
        let child = allDic.filter(f => {
            return pobj.id == f.pid;
        });
        if (child && child.length > 0) {
            pobj.children = child;
            child.forEach(chi => {
                loopDic(chi, allDic);
            })
        }
    }
}

//接口回调函数
class DictionaryController {
    async saveData(ctx, next) {
        //1. 获取数据
        const data = ctx.request.body
        try {
            //2. 操作数据库
            const res = await saveBase(Dictionary, data, "id");
            //3. 返回结果
            ctx.body = resSuccess(res);
        } catch (err) {
            throw throwError(err, errDoMsg.SAVEUPD);
        }
    }

    async mapDictionary(ctx, next) {
        //1. 获取数据
        const data = ctx.request.body

        try {
            //参数 code:[1] type:type tree:fase
            //2. 操作数据库
            let codes = data.code;
            let or = [{code: codes}];
            if (data.tree === true) or.push({pid: codes})
            let where = {type: data.type ? data.type : "基础字典", [Op.or]: or};
            let dt = await listBase(Dictionary, where);
            let res = [];
            if (data.tree === true) {
                res = dt.filter(f => {
                    return codes.includes(f.code);
                });
                res.forEach(f => {
                    loopDic(f, dt);
                });
            } else {
                res = dt;
            }
            //3. 返回结果
            let obj = {};
            res.forEach(f => {
                obj[f.code] = f;
            });
            ctx.body = resSuccess(obj);
        } catch (err) {
            throw throwError(err, errDoMsg.SELECT);
        }
    }

    async delDictionary(ctx, next) {
        const data = ctx.request.body
        try {
            let where = {id: data.id}
            const res = await delBase(Dictionary, where);
            ctx.body = resBool(res);
        } catch (err) {
            throw throwError(err, errDoMsg.DEL);
        }
    }
}

module.exports = new DictionaryController()